package com.yvan.serverless.jdbc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

public class DaoResultTransformService implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    public void convert(Map<String, Object> dataRow) {
        if (dataRow == null) {
            return;
        }
        Map<String, DaoResultConvert> convertMap = this.applicationContext.getBeansOfType(DaoResultConvert.class);

        for (Map.Entry<String, Object> entry : dataRow.entrySet()) {
            // 逐个属性查找
            for (DaoResultConvert convert : convertMap.values()) {
                if (convert.isMatch(dataRow, entry.getKey(), entry.getValue())) {
                    // 找到匹配的转换器
                    dataRow.put(entry.getKey(), convert.transform(dataRow, entry.getKey(), entry.getValue()));
                    break;
                }
            }
        }
    }
}
